package industry_2024.industry_05.extract

import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions.lit

import java.text.SimpleDateFormat
import java.util.{Calendar, Properties}

object extract_count {
  def main(args: Array[String]): Unit = {
    val spark=SparkSession.builder()
      .master("local[*]")
      .appName("数据抽取")
      .config("hive.exec.dynamic.partition.mode","nonstrict")
      .enableHiveSupport()
      .getOrCreate()

    val mysql_connect=new Properties()
    mysql_connect.setProperty("user","root")
    mysql_connect.setProperty("password","123456")
    mysql_connect.setProperty("driver","com.mysql.jdbc.Driver")

    val day:Calendar=Calendar.getInstance()
    day.add(Calendar.DATE,-1)
    val yesterday=new SimpleDateFormat("yyyyMMdd").format(day.getTime)

    spark.sql("use ods05")

    //  定义将数据全量抽取到hive的方法
    def to_hive(mysql_table:String,hive_table:String):Unit={
      //  第三题需要剔除字段
          if(hive_table=="producerecord"){
            val mysql_data=spark.read.jdbc("jdbc:mysql://192.168.40.110:3306/shtd_industry?useSSL=false","ProduceRecord",mysql_connect)
              .drop("ProducePrgCode")
              .withColumn("etldate",lit(yesterday))

            mysql_data.write.mode("append")
              .format("hive")
              .partitionBy("etldate")
              .saveAsTable(hive_table)
          }
     // 其余题不需要剔除字段
      else{
              val mysql_data=spark.read.jdbc("jdbc:mysql://192.168.40.110:3306/shtd_industry?useSSL=false",s"${mysql_table}",mysql_connect)
                .withColumn("etldate",lit(yesterday))
            mysql_data.write.mode("append")
              .format("hive")
              .partitionBy("etldate")
              .saveAsTable(hive_table)
          }
    }

    to_hive("ChangeRecord","changerecord")
    to_hive("BaseMachine","basemachine")
    to_hive("ProduceRecord","producerecord")
    to_hive("MachineData","machinedata")




    spark.close()
  }

}
